package com.huluobo.base.net

import android.util.Log
import com.blankj.utilcode.util.EncryptUtils
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.Response
import okio.Buffer
import org.json.JSONObject

/**
 *  Created by LC on 2024/8/20.
 */
class SignInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        val builder = request.newBuilder()

        //1.拿到请求体
        val body = chain.request().body  //{"token":"kajsbksjdfnlakshyiquhwknek"}
        val buffer = Buffer() //字符拼接器
        body?.writeTo(buffer) //到此,body被写入到了字符串拼接器
        val bodyStr = buffer.toString()//把拼接器转换为String
        Log.i("TagA", "interceptor bodyStr :$bodyStr")
        buffer.close()

        //2.截取json数据
        val jsonStr = bodyStr.substring(bodyStr.indexOf("{"), bodyStr.lastIndexOf("}") + 1)//去掉字符串的大括号
        Log.i("TagA", "interceptor jsonStr:$jsonStr")

        //3.获取键值对
        val sb = StringBuffer()
        val jsonObject = JSONObject(jsonStr)
        val keys = jsonObject.keys()
        while (keys.hasNext()) {
            val key = keys.next()
            val value = jsonObject.getString(key)
            //拼接签名
            sb.append(value)
        }

        //5.拼接秘钥
        sb.append("tamboo")
        Log.i("TagA", "interceptor sb:${sb.toString()}")

        //6.MD5加密,并且转换为小写
        val sign = EncryptUtils.encryptMD5ToString(sb.toString()).toLowerCase()

        //7.新的请求body
        jsonObject.put(Const.PARAM_SIGN, sign)
        Log.i("TagA", "interceptor sign:$sign")
        val requestBody = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), jsonObject.toString())
        builder.post(requestBody)
        request = builder.build()
        return chain.proceed(request)
    }
}